﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using DevExpress.XtraPrinting;
using System.Data.SqlClient;
using GeneralLibs;

namespace ReportGenerators.CongNo
{
    public partial class FrmChiTietCongNoKetHop : BasicForms.FrmSupportPrintableComponents
    {
        public FrmChiTietCongNoKetHop()
        {
            InitializeComponent();
        }

        private void FrmChiTietCongNoKetHop_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedText = "Tùy chọn";

                cmbDoiTac.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucDoiTac().DataView;
                cmbDoiTac.DisplayColumn = "Ten";
                cmbDoiTac.ValueColumn = "ID";
                cmbDoiTac.AddVisibleColumn("Ma", "Mã");
                cmbDoiTac.AddVisibleColumn("Ten", "Tên");
                cmbDoiTac.EditValue = Guid.Empty;

                DataView dvTaiKhoan = DanhMucTaiKhoan.GetByLoaiTaiKhoan(LoaiTaiKhoan.CongNo).DataView;
                #region cmbTaiKhoan
                cmbTaiKhoanNoPhaiThu.DataSource = dvTaiKhoan;
                cmbTaiKhoanNoPhaiThu.DisplayColumn = "Ten";
                cmbTaiKhoanNoPhaiThu.ValueColumn = "ID";
                cmbTaiKhoanNoPhaiThu.AddVisibleColumn("SoHieu", "Số hiệu");
                cmbTaiKhoanNoPhaiThu.AddVisibleColumn("Ten", "Tên");
                cmbTaiKhoanNoPhaiThu.EditValue = DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("PhaiThuKhachHang");

                cmbTaiKhoanNoPhaiTra.DataSource = dvTaiKhoan;
                cmbTaiKhoanNoPhaiTra.DisplayColumn = "Ten";
                cmbTaiKhoanNoPhaiTra.ValueColumn = "ID";
                cmbTaiKhoanNoPhaiTra.AddVisibleColumn("SoHieu", "Số hiệu");
                cmbTaiKhoanNoPhaiTra.AddVisibleColumn("Ten", "Tên");
                cmbTaiKhoanNoPhaiTra.EditValue = DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("PhaiTraNhaCungCap");
                #endregion

                dsChiTietCongNoKetHop = new ReportGenerators.CongNo.ChiTietCongNoKetHop.DsChiTietCongNoKetHop();
                gridControl.DataSource = dsChiTietCongNoKetHop.Detail_ChiTietCongNoKetHop;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbDoiTac_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbDoiTac.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                string doiTacCondition = "1 = 1";
                if (cmbDoiTac.EditValue is Guid && (Guid)cmbDoiTac.EditValue != Guid.Empty) doiTacCondition = string.Format("'{0}'", cmbDoiTac.EditValue);
                else
                {
                    FrmWarning.Show("Cảnh báo", "Chưa nhập đối tác");
                    return;
                }

                cmd.CommandText = string.Format("SELECT TBL.Ngay, SoChungTu, PThuoc.So SoPhieu, LoaiChungTu, TBL.DienGiai, TangPhaiThu, GiamPhaiThu,  \n" +
                                               "		TangPhaiTra, GiamPhaiTra, DuPhaiTra,  Du 		 \n" +
                                               "FROM ( \n" +
                                               "SElECT C.ChungTuID, A.Ngay, C.So SoChungTu, D.Ten LoaiChungTu, C.DienGiai, SUM(A.GiaTri) TangPhaiThu, CAST(0 AS money) GiamPhaiThu, CAST(0 AS money) DuPhaiThu, \n" +
                                               "                                   CAST(0 AS money) TangPhaiTra, CAST(0 AS money) GiamPhaiTra, CAST(0 AS money) DuPhaiTra, \n" +
                                               "                                   CAST(0 AS money) Du	" +
                                               "FROM ButToan A INNER JOIN TaiKhoan B ON A.TaiKhoanNoID = B.ID AND B.SoHieu LIKE '131' \n" +
                                               "				INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                                               "				INNER JOIN LoaiChungTu D ON C.LoaiChungTuID = D.ID \n" +
                                               "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <=@ThoiDiemCuoi AND A.DoiTuongNghiepVuNoID = {0}\n" +
                                               "GROUP BY A.Ngay, C.So, C.DienGiai, D.Ten, C.ChungTuID			 \n" +
                                               "UNION \n" +
                                               "SElECT C.ChungTuID, A.Ngay, C.So SoChungTu,  D.Ten LoaiChungTu, C.DienGiai, CAST(0 AS money) TangPhaiThu, SUM(A.GiaTri) GiamPhaiThu, CAST(0 AS money) DuPhaiThu, \n" +
                                               "									CAST(0 AS money) TangPhaiTra, CAST(0 AS money) GiamPhaiTra, CAST(0 AS money) DuPhaiTra, \n" +
                                               "									CAST(0 AS money) Du \n" +
                                               "FROM ButToan A INNER JOIN TaiKhoan B ON A.TaiKhoanCoID = B.ID AND B.SoHieu LIKE '131' \n" +
                                               "				INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                                               "				INNER JOIN LoaiChungTu D ON C.LoaiChungTuID = D.ID \n" +
                                               "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <=@ThoiDiemCuoi AND A.DoiTuongNghiepVuCoID = {0}\n" +
                                               "GROUP BY A.Ngay, C.So, C.DienGiai, D.Ten, C.ChungTuID \n" +
                                               "UNION \n" +
                                               "SElECT C.ChungTuID, A.Ngay, C.So SoChungTu,  D.Ten LoaiChungTu,C.DienGiai, CAST(0 AS money) TangPhaiThu, CAST(0 AS money) GiamPhaiThu, CAST(0 AS money) DuPhaiThu, \n" +
                                               "									SUM(A.GiaTri) TangPhaiTra, CAST(0 AS money) GiamPhaiTra, CAST(0 AS money) DuPhaiTra, \n" +
                                               "									CAST(0 AS money) Du \n" +
                                               "FROM ButToan A INNER JOIN TaiKhoan B ON A.TaiKhoanCoID = B.ID AND B.SoHieu LIKE '331' \n" +
                                               "				INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                                               "				INNER JOIN LoaiChungTu D ON C.LoaiChungTuID = D.ID \n" +
                                               "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <=@ThoiDiemCuoi AND A.DoiTuongNghiepVuCoID = {0}\n" +
                                               "GROUP BY A.Ngay, C.So, C.DienGiai, D.Ten, C.ChungTuID \n" +
                                               "UNION \n" +
                                               "SElECT C.ChungTuID, A.Ngay, C.So SoChungTu,  D.Ten LoaiChungTu, C.DienGiai, CAST(0 AS money) TangPhaiThu, CAST(0 AS money)  GiamPhaiThu, CAST(0 AS money) DuPhaiThu, \n" +
                                               "									CAST(0 AS money) TangPhaiTra, SUM(A.GiaTri) GiamPhaiTra, CAST(0 AS money) DuPhaiTra, \n" +
                                               "									CAST(0 AS money) Du \n" +
                                               "FROM ButToan A INNER JOIN TaiKhoan B ON A.TaiKhoanNoID = B.ID AND B.SoHieu LIKE '331' \n" +
                                               "				INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                                               "				INNER JOIN LoaiChungTu D ON C.LoaiChungTuID = D.ID \n" +
                                               "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <=@ThoiDiemCuoi AND A.DoiTuongNghiepVuNoID = {0}\n" +
                                               "GROUP BY A.Ngay, C.So, C.DienGiai, D.Ten, C.ChungTuID \n" +
                                               ") AS TBL LEFT JOIN ChungTu PThuoc ON TBL.ChungTuID = PThuoc.ChungTuGocID \n" +
                                               "ORDER BY TBL.Ngay  \n",
                                               doiTacCondition);

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                if (dsChiTietCongNoKetHop != null) dsChiTietCongNoKetHop.Detail_ChiTietCongNoKetHop.Clear();
                da.Fill(dsChiTietCongNoKetHop.Detail_ChiTietCongNoKetHop);

                SoDuTheoDoiTuong soDuPhaiThuDauKy = SoDuTheoDoiTuong.CalculateFromDB(cmd, ngayBatDau, (Guid)cmbTaiKhoanNoPhaiThu.EditValue, (Guid)cmbDoiTac.EditValue);
                SoDuTheoDoiTuong soDuPhaiTraDauKy = SoDuTheoDoiTuong.CalculateFromDB(cmd, ngayBatDau, (Guid)cmbTaiKhoanNoPhaiTra.EditValue, (Guid)cmbDoiTac.EditValue);
                DataRow rowDauKy = dsChiTietCongNoKetHop.Detail_ChiTietCongNoKetHop.NewRow();
                rowDauKy["Ngay"] = ngayBatDau;
                rowDauKy["DienGiai"] = "Đầu kỳ";
                rowDauKy["TangPhaiThu"] = 0;
                rowDauKy["GiamPhaiThu"] = 0;
                rowDauKy["DuPhaiThu"] = soDuPhaiThuDauKy.DuNo - soDuPhaiThuDauKy.DuCo;
                rowDauKy["TangPhaiTra"] = 0;
                rowDauKy["GiamPhaiTra"] = 0;
                rowDauKy["DuPhaiTra"] = soDuPhaiTraDauKy.DuCo - soDuPhaiTraDauKy.DuNo;
                rowDauKy["Du"] = (decimal)rowDauKy["DuPhaiThu"] - (decimal)rowDauKy["DuPhaiTra"];
                dsChiTietCongNoKetHop.Detail_ChiTietCongNoKetHop.Rows.InsertAt(rowDauKy, 0);

                decimal tempDuPhaiThu = (decimal)rowDauKy["DuPhaiThu"];
                decimal tempDuPhaiTra = (decimal)rowDauKy["DuPhaiTra"];
                foreach (DataRow row in dsChiTietCongNoKetHop.Detail_ChiTietCongNoKetHop.Rows)
                {
                    row["DuPhaiThu"] = tempDuPhaiThu + (decimal)row["TangPhaiThu"] - (decimal)row["GiamPhaiThu"];
                    tempDuPhaiThu = (decimal)row["DuPhaiThu"];

                    row["DuPhaiTra"] = tempDuPhaiTra + (decimal)row["TangPhaiTra"] - (decimal)row["GiamPhaiTra"];
                    tempDuPhaiTra = (decimal)row["DuPhaiTra"];

                    row["Du"] = tempDuPhaiThu - tempDuPhaiTra;
                }

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
        }

        private void gridView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
                e.Info.DisplayText = (e.RowHandle).ToString();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string option1 = string.Format("Từ {0}:{1} ngày {2}/{3}/{4} đến {5}:{6} ngày {7}/{8}/{9}",
                             dtNgayBatDau.DateTime.Hour, dtNgayBatDau.DateTime.Minute,
                             dtNgayBatDau.DateTime.Day, dtNgayBatDau.DateTime.Month, dtNgayBatDau.DateTime.Year,
                             dtNgayKetThuc.DateTime.Hour, dtNgayKetThuc.DateTime.Minute,
                             dtNgayKetThuc.DateTime.Day, dtNgayKetThuc.DateTime.Month, dtNgayKetThuc.DateTime.Year);
            string option2 = "";
           
            if (cmbDoiTac.EditValue is Guid && (Guid)cmbDoiTac.EditValue != Guid.Empty)
            {
                option2 = string.Format("Đối tác: {0} - {1}  ", 
                                DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTac.EditValue).Ma,
                                DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTac.EditValue).Ten);
            }
            option2 += string.Format("TK phải thu: {0} TK phải trả: {1}",
                                DanhMucTaiKhoan.Instance.GetByID((Guid)cmbTaiKhoanNoPhaiThu.EditValue).SoHieu,
                                DanhMucTaiKhoan.Instance.GetByID((Guid)cmbTaiKhoanNoPhaiTra.EditValue).SoHieu);

            PrintWithHeaderAndFooter(true, gridControl, true, true, "Sổ chi tiết công nợ phải thu phải trả", option1, option2,
                                            string.Format("XÁC NHẬN CỦA {0}", GeneralLibs.Config.TenDoanhNghiep),
                                            "XÁC NHẬN CỦA ĐỐI TÁC "
                                    );
        }

        //void printableComponentLink_CreateReportFooterArea(object sender, CreateAreaEventArgs e)
        //{
        //    e.Graph.BackColor = Color.White;
        //    string tenCongTy = string.Format("Xác nhận của {0}", GeneralLibs.Config.TenDoanhNghiep);
        //    e.Graph.StringFormat = new BrickStringFormat(StringAlignment.Near);
        //    e.Graph.Font = new Font("Times New Roman", 12, FontStyle.Regular);
        //    RectangleF rectCongTy = new RectangleF(0, 30, 300, 60);
        //    e.Graph.DrawString(tenCongTy, Color.Black, rectCongTy, BorderSide.None);
        //}
    }
}
